package com.bulletelc.apollopre.module.main.center.orders.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.OrderDetailBean;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.module.main.MainActivity;
import com.bulletelc.apollopre.module.main.center.orders.OrderListAdapter;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author: lhl
 * date  : 2018/2/3
 * desc  : 订单状态的fragment, 所有订单、代付款、待发货、待签收、待评价的模板
 */

public class OrderStateFragment extends MVPBaseFragment<OrderStateContract.View, OrderStatePresenter> implements OrderStateContract.View,
        View.OnClickListener, ExpandableListView.OnGroupClickListener, OnLoadmoreListener, OrderListAdapter.OnClickListener {

    // views
    private RelativeLayout rlNoOrder;
    private TextView btnStroll; //去逛逛
    private SmartRefreshLayout smartRefreshLayout;
    private ExpandableListView elvOrder;

    // data
    private OrderListAdapter orderListAdapter;
    private List<OrderDetailBean> orderDetailBeans;
    private int orderState; // 订单状态
    private int commentState; // 订单评论状态
    private int pageCount; //  总页数
    private int page = 1; // 当前页，默认第一页
    private int groupPosition; // 记录下点击的btnCancelOrder的位置
    private boolean first = true; // 是否第一次加载

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!first) {
                orderDetailBeans.clear();
                orderListAdapter.notifyDataSetChanged();
                page = 1;
                getOrderList(page);
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        orderDetailBeans.clear();
        orderListAdapter.notifyDataSetChanged();
        page = 1;
        getOrderList(page);
        first = false;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.order_list_fragment;
    }

    @Override
    public void assignViews() {
        rlNoOrder = findView(R.id.rlNoOrder);
        btnStroll = findView(R.id.btnStroll);
        smartRefreshLayout = findView(R.id.smartRefreshLayout);
        elvOrder = findView(R.id.elvOrder);
    }

    @Override
    public void setListener() {
        btnStroll.setOnClickListener(this);
        smartRefreshLayout.setOnLoadmoreListener(this);
        elvOrder.setOnGroupClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            orderState = bundle.getInt(IntentCode.EXTRA_KEY_ORDER_STATE);
            commentState = bundle.getInt(IntentCode.EXTRA_KEY_ORDER_COMMENT_STATE);
        }

        orderDetailBeans = new ArrayList<>();
        orderListAdapter = new OrderListAdapter(getContext(), orderDetailBeans);
        elvOrder.setAdapter(orderListAdapter);
        orderListAdapter.setOnClickListener(this);
        //expandListView();

        smartRefreshLayout.setEnableRefresh(false);//禁止下拉刷新功能

    }

    @Override
    protected OrderStatePresenter createPresenter() {
        return new OrderStatePresenter();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnStroll://去逛逛
                Intent intent = new Intent(baseActivity, MainActivity.class);
                intent.putExtra(IntentCode.EXTRA_KEY_FRAGMENT_POSITION, 0);
                startActivity(intent);
                break;
        }
    }

    @Override
    public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
        return true;
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        if (page <= pageCount) {
            getOrderList(page);
        } else {
            Toast.makeText(baseActivity, "没有更多数据", Toast.LENGTH_SHORT).show();
        }
        refreshlayout.finishLoadmore(true);
    }

    @Override
    public void onSuccess(List<OrderDetailBean> orderDetailBeans, int pageCount) {
        this.pageCount = pageCount;
        if (orderDetailBeans != null && filterEmptyOrder(orderDetailBeans).size() > 0) {
            if (page == 1) {
                this.orderDetailBeans.clear();
            }
            this.orderDetailBeans.addAll(filterEmptyOrder(orderDetailBeans));
            orderListAdapter.notifyDataSetChanged();
            expandListView();
        } else {
            rlNoOrder.setVisibility(View.VISIBLE);
            smartRefreshLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onFail(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(String error) {
        ToastUtil.showLongToast(getContext(), R.string.network_msg);
    }

    @Override
    public void onSuccessCancelOrder() {
        Toast.makeText(baseActivity, "取消成功", Toast.LENGTH_SHORT).show();
        if (orderState == GlobalConfig.ORDER_STATE_UN_PAID) {//未支付订单
            orderDetailBeans.remove(groupPosition);
            if (orderDetailBeans.size() > 0) {
                orderListAdapter.notifyDataSetChanged();
            } else {
                rlNoOrder.setVisibility(View.VISIBLE);
                smartRefreshLayout.setVisibility(View.GONE);
            }
        } else if (orderState == 0) { //所有订单
            orderDetailBeans.get(groupPosition).setState(GlobalConfig.ORDER_STATE_CANCEL);
            orderDetailBeans.get(groupPosition).setState_label("订单取消");
            orderListAdapter.notifyDataSetChanged();

        }

    }

    @Override
    public void onFailCancelOrder(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorCancelOrder(String error) {
        ToastUtil.showLongToast(getContext(), R.string.network_msg);
    }


    /**
     *
     */
    public void sendMessage() {
        Message message = handler.obtainMessage();
        message.sendToTarget();
    }

    /**
     * 获取订单列表
     */
    private void getOrderList(int page) {
        if (orderState == 0) {
            presenter.getOrderList(page);
        } else {
            String json = getJson(orderState, commentState);
            if (json != null) {
                presenter.getOrderList(json, page);
            } else {
                Toast.makeText(baseActivity, "请求参数有误", Toast.LENGTH_SHORT).show();
            }
        }

    }

    /**
     * 获取请求的json参数
     */
    private String getJson(int state, int commentState) {
        JSONObject subObj = new JSONObject();
        JSONObject object = new JSONObject();
        String json;
        try {
            subObj.put("state", state);
            if (commentState != 0) {
                subObj.put("comment_state", commentState);
            }
            object.put("SalesOrder", subObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        json = object.toString();
        return json;
    }

    /**
     * 将listview的子listview展开
     */
    private void expandListView() {
        for (int i = 0, size = orderListAdapter.getGroupCount(); i < size; i++) {
            elvOrder.expandGroup(i);
        }
    }

    /**
     * 过滤空的订单
     *
     * @return
     */
    private List<OrderDetailBean> filterEmptyOrder(List<OrderDetailBean> orderDetailBeans) {
        List<OrderDetailBean> newOrderDetailBeanList = new ArrayList<>();
        for (int i = 0, size = orderDetailBeans.size(); i < size; i++) {
            OrderDetailBean orderDetailBean = orderDetailBeans.get(i);
            if (orderDetailBean.getSales_order_items().size() > 0) {
                newOrderDetailBeanList.add(orderDetailBean);
            }
        }
        return newOrderDetailBeanList;
    }

    /**
     * 显示用户确认取消订单的提示框
     *
     * @param groupPosition
     */
    private void showDialog(final int groupPosition) {
        AlertDialog dialog = new AlertDialog.Builder(baseActivity)
                .setMessage("您确定取消此订单吗？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        cancelOrder(groupPosition);
                    }
                }).create();
        dialog.show();


    }

    /**
     * 取消订单
     *
     * @param groupPosition
     */
    private void cancelOrder(int groupPosition) {
        this.groupPosition = groupPosition;
        String json = null;
        JSONObject object = new JSONObject();
        try {
            object.put("state", GlobalConfig.ORDER_STATE_CANCEL);
            object.put("id", orderDetailBeans.get(groupPosition).getId());
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (json != null) {
            presenter.cancelOrder(json);
        } else {
            Toast.makeText(baseActivity, "请求参数有误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(int groupPosition) {
        showDialog(groupPosition);
    }
}
